#coding=utf-8
import os, subprocess, sys, urllib, socket,re

def print_red(s):
  print '\033[0;31;48m%s\033[0m'%s
  
proxy_program = '/home/jay/py/gappproxy/localproxy/proxy.py'

def start_proxy(app_id, port, type_='http'):
    command = ['python', proxy_program, '-t', type_,  '-a', app_id, '-p', port]
    p = subprocess.Popen(command, stderr=open('/dev/null', 'w'), stdout=open('/dev/null', 'w'))

def stop_proxy(pid):
    subprocess.Popen(['kill', pid])
    
def check_running_proxy():
    result = {'reverse':[] ,'http':[]}
    
    command = 'ps aux|grep proxy.py|grep -v grep'
    r = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE).communicate()[0]
    data = [re.split(r'\s+', i) for i in r.split('\n') if i]
    
    for d in data:
        #print d
        if d[-5] == 'reverse':
            result['reverse'] = [ d[-3], d[-5], d[-1], d[1] ]
        else:
            result['http'].append([ d[-3], d[-5], d[-1], d[1] ])
      
    return result
    
http_url = 'http://%s.appspot.com/fetch.py'
https_url = 'https://%s.appspot.com/fetch.py'
reverse_url = 'http://%s.jayproxy.com/fetch.py'
urls = {'http':http_url, 'https':https_url, 'reverse':reverse_url}
  
def check_connect(app_id, type_='http'):
    url = urls[type_]
    
    socket.setdefaulttimeout(5)
    try:
        f = urllib.urlopen(url%app_id)  
    except IOError,e:
        '''
        errno, errstr = sys.exc_info()[:2]
        if str(errstr).find('timed out') !=-1:
            return False
        if str(errstr).find('reset') !=-1:
            return False
        '''
        #print app_id, e
        return False
    else:
        code = f.getcode()
        #print code
        if code == 200:
            return True
        else:
            return False

if __name__ == '__main__':
    from apps import apps

    #net
    http_available = []
    reverse_available = []

    for a in apps:
        print a
        if check_connect(a, 'http'): http_available.append(a)
        if check_connect(a, 'reverse'): reverse_available.append(a)
        
    not_available = list(set(apps)-set(reverse_available))
    print_red('app 网络连接情况:')
    print 'Http:',http_available
    print 'Reverse:', reverse_available
    print '无法连接上的:', not_available
    
    #mem
    print_red('app 进程运行情况:')
    result = check_running_proxy()
    #print result
    r = result.get('reverse', None)
    if r:
        print '以reverse方式运行:%s(pid:%s) runing on %s'%(r[0], r[3], r[2])
    hs = result['http']
    if hs:print('以http方式运行:')
    for h in hs:
        print '%s(pid:%s) runing on %s'%(h[0], h[3], h[2])
        
         
